export const processInParallel = <T, R extends any[]>(
  items: T[],
  processFn: (item: T) => Promise<R>,
  maxConcurrent: number,
  onChunkFinish?: (data: R) => void
) => {
  let isPaused = false;
  let resolvePause: (() => void) | null = null;

  const pause = () => {
    isPaused = true;
    console.log('已暂停');
    
    return new Promise<void>(resolve => {
      resolvePause = resolve;
    });
  };

  const resume = () => {
    isPaused = false;
    if (resolvePause) {
      resolvePause();
      resolvePause = null;
    }
  };

  const process = async (): Promise<R[number][]> => {
    const results: R[number][] = [];
    let currentIndex = 0;
    const runningTasks: Promise<any>[] = [];
    
    while (currentIndex < items.length || runningTasks.length > 0) {
      if (isPaused) {
        await new Promise(resolve => {
          resolvePause = resolve as () => void;
        });
      }
      // 填充运行队列
      while (runningTasks.length < maxConcurrent && currentIndex < items.length) {
        const task = processFn(items[currentIndex])
          .then(res => {
            onChunkFinish?.(res);
            results.push(res)
          })
          .finally(() => {
            runningTasks.splice(runningTasks.indexOf(task), 1);
          });
        runningTasks.push(task);
        currentIndex++;
      }
    
      // 等待任一任务完成
      if (runningTasks.length > 0) {
        await Promise.race(runningTasks);
      }
    }
  
    return results.flat();
  };

  return {
    promise: process(),
    pause,
    resume
  };
}

export const chunkArray = <T>(arr: T[], size: number) => {
  return Array.from({ length: Math.ceil(arr.length / size) }, (_, i) =>
    arr.slice(i * size, i * size + size)
  )
}
